//
//  PhotoBrowserViewController.swift
//  XDweibo
//
//  Created by HanXingda on 15/7/5.
//  Copyright © 2015年 韩兴达. All rights reserved.
//

import UIKit
import FFAutoLayout
import SVProgressHUD

class PhotoBrowserViewController: UIViewController,PhotoBrowserCollectionViewCellDelegate {

    
    //保存按钮的点击事件
    func savePhoto() {
        // 0. 拿到当前的cell
        let indexPath = collectionView.indexPathsForVisibleItems().last
        let cell = collectionView.cellForItemAtIndexPath(indexPath!) as! PhotoBrowserCollectionViewCell
        
        // 1. 拿到图像
        let image = cell.imageView.image!
        
        // 2. 保存图像 - 回调方法的参数格式是固定的
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    // - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image :UIImage, didFinishSavingWithError error:NSError?, contextInfo :AnyObject) {
        
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存出错")
        } else {
            SVProgressHUD.showSuccessWithStatus("保存成功")
        }
    }
    

    //关闭按钮的点击事件
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    //准备视图布局
    func prepareLayout() {
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        collectionView.pagingEnabled = true
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
    }
    //准备collectionView
    func prepareCollectionView() {
        collectionView.dataSource = self
        collectionView.registerClass(PhotoBrowserCollectionViewCell.self, forCellWithReuseIdentifier: XDPhotoBrowserCellReuseIdentifier)
    }
    init(index:Int, urls:[NSURL]) {
        currentIndex = index
        imageURLs = urls
        super.init(nibName: nil, bundle: nil)
    }
    
     override func viewDidLoad() {
        super.viewDidLoad()
       
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        prepareLayout()
        let indexPath = NSIndexPath(forItem: currentIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        view.addSubview(collectionView)
        view.addSubview(saveButton)
        view.addSubview(closeButton)
        
        //设置布局
        collectionView.ff_Fill(view)
        
        //保存按钮
        saveButton.ff_AlignInner(ff_AlignType.BottomRight, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: -12, y: -12))

        //关闭按钮
        closeButton.ff_AlignInner(ff_AlignType.BottomLeft, referView: view, size: CGSize(width: 60, height: 30), offset: CGPoint(x: 12, y: -12))
        
        //准备collectionView
        prepareCollectionView()
        
        //按钮的点击事件
        saveButton.addTarget(self, action: "savePhoto", forControlEvents: UIControlEvents.TouchUpInside)
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
    }
    // MARK: - PhotoBrowserCollectionViewCellDelegate
    func didSelctedCurrentImage() {
        close()
    }
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // 图像数组
    private var imageURLs: [NSURL]
    // 用户选中的图像索引
    private var currentIndex: Int
    
    //懒加载
    lazy var layout = UICollectionViewFlowLayout()
    
    lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    //保存按钮
    lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14)
    //关闭按钮
    lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14)
    //注册Cell-ID
    private let XDPhotoBrowserCellReuseIdentifier = "XDPhotoBrowserCellReuseIdentifier"
}

extension PhotoBrowserViewController: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageURLs.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XDPhotoBrowserCellReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowserCollectionViewCell
        cell.photoDelegate = self
        cell.backgroundColor = UIColor.randomColor()
        cell.imageURLs = imageURLs[indexPath.item]
        
        return cell
        
    }
}
